var express = require('express');
var UserSchema = require('../../modules/users');
var router = express.Router();
//列表显示 搜索查询
router.get('/list', function(req, res, next) {
  // 初始化参数
  let page = req.query.page ? parseInt(req.query.page) : 1;
  let limit = req.query.limit ? parseInt(req.query.limit) : 10;

  // 查询参数
  let searchData = {};
  req.query.campus ? searchData.campus = { $regex: req.query.campus } : '';
  req.query.username ? searchData.username = { $regex: req.query.username } : '';
  req.query.level ? searchData.level = { $regex: req.query.level } : '';
  req.query.college ? searchData.college = { $regex: req.query.college } : '';
  req.query.class ? searchData.class = { $regex: req.query.class } : '';
  req.query.name ? searchData.name = { $regex: req.query.name } : '';
  
  if (typeof page !== 'number' || typeof limit !== 'number') {
    res.json({code: 500, msg: 'querys is type error'});
    return res.end();
  }

  new Promise((resolve, reject)=>{
    UserSchema.paginate(searchData, { page: page, limit: limit }, function(err, result) {
      if (!err) {
        resolve(result);
      }else {
        reject(err);
      }
    });
  }).then(response=>{
    res.json({
      code: 200,
      data: response.docs,
      count: response.total,
      pages: response.pages
    });
    return res.end();
  }).catch(error=>{
    res.json({code: 500, msg: error, query: req.query});
    return res.end();
  });
});
//删除
router.post('/del', function (req, res, next) {
  if (!req.body.id) {
    res.json({code: 500, msg: '缺少参数id'});
    return res.end();
  }
  UserSchema.findOne({_id: req.body.id}).exec((err, doc)=>{
    if (!err && doc) {
      UserSchema.remove({_id: doc._id}, (err) => {
        if (!err) {
          res.json({code: 200, msg: '成功删除用户！'});
          return res.json();
        } else {
          res.status(500);
          res.json({code: 10000, msg: '数据库异常，删除失败'});
          return res.end();
        }
      });
    } else {
      res.status(500);
      res.json({code: 10000, msg: '数据库异常，查询失败'});
      return res.end();
    }
  });
});
//新增
router.post('/add', function(req, res, next) {
  let username = req.body.username;

  new Promise((resolve, reject)=>{
    var query  = UserSchema.where({ 'username': username });
    query.findOne(function (err, doc){
      if (!err && !doc) {
        resolve();
      }else {
        reject(err);
      }
    });
  }).then(()=>{
    let insertData = new UserSchema({
      'createTime': new Date().getTime(),
      'level' : req.body.level ? req.body.level : '',
      'username': req.body.username ? req.body.username : '',
      'password': req.body.password ? req.body.password : '',
      'campus': req.body.campus ? req.body.campus : '',
      'class': req.body.class ? req.body.class : '',
      'name': req.body.name ? req.body.name : '',
      'college': req.body.college ? req.body.college : '',
    }, false);
    insertData.save(function (err) {
      if (err) {
        res.json({code: 401, msg: '新增失败，请重试！'});
        return res.end();
      } else {
        res.json({code: 200, msg: '新增成功！' });
        return res.end();
      }
    });
  }).catch(()=>{
    res.json({code: 500, msg: '该用户已存在！'});
    return res.end();
  });
});
//编辑
router.post('/upd', function(req, res, next){
  let data = req.body
  UserSchema.findByIdAndUpdate({ _id: data._id }, {$set: {
    'updateTime': new Date().getTime(),
    'username': req.body.username ? req.body.username : '',
    'password': req.body.password ? req.body.password : '',
    'campus': req.body.campus ? req.body.campus : '',
    'level' : req.body.level ? req.body.level : '',
    'class': req.body.class ? req.body.class : '',
    'name': req.body.name ? req.body.name : '',
    'college': req.body.college ? req.body.college : '',
  }}, function (err, raw) {
    if (!err) {
      res.json({code: 200, msg: '更新成功'});
      return res.end();
    } else {
      res.json({code: 500, msg: '更新失败'});
      return res.end();
    }
  }); 
});
module.exports = router;
